package model;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import javax.imageio.ImageIO;

/**
 *
 * @author Dustin & Maik
 */
public class WebObject {

    protected byte[] content;
    protected URL url;
    private boolean isImage;

    public WebObject(URL anUrl, boolean anImage) {
        url = anUrl;
        isImage = anImage;
    }

    public void writeToFile() {
        String filepath = "";
        filepath += "nu.nl";
        filepath += url.getPath();
        filepath += url.getPath().matches(".*/$") ? "index.html" : "";

        File outputFile = new File(filepath);
        outputFile.getParentFile().mkdirs();

        BufferedReader bufferedReader;
        String data = "";
        if (isImage) {
            try {
                System.out.println(url.toString());
                BufferedImage bufferedImage = ImageIO.read(url);
                if(bufferedImage != null) {
                    File file = new File(filepath);
                    ImageIO.write(bufferedImage,"jpg",file);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } else {
            System.out.println("CSS: "+url.toString());
            try {
                bufferedReader = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()));

                String inputLine;
                while ((inputLine = bufferedReader.readLine()) != null) {
                    data += inputLine + "\n";
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            content = data.getBytes();

            try {
                FileOutputStream foStream = new FileOutputStream(outputFile);
                foStream.write(content);
                foStream.close();
            } catch (FileNotFoundException ex) {
                //ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

